package com.atguigu.boot04.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author:朱思博
 * @date:2021/5/8-{13:35}   文件上传与下载
 */
@Controller
@Slf4j
public class FormController {
    @GetMapping("/form_layouts")
    public String form_layouts() {
        log.info("进来了");
        return "form/form_layouts";
    }

    // MutipartFile自动封装上传来的文件
    @PostMapping("/upload")
    public String upload(
            @RequestParam("email") String email,
            @RequestParam("username") String username,
            @RequestPart("headerImg") MultipartFile headerImg,  // 单文件上传，注意注解是@RequestPart了
            @RequestPart("photos") MultipartFile[] photos
            ) throws IOException {

        log.info("上传的信息:email = {},username = {},headerImg大小 = {},photos个数 = {}",
                email,username,headerImg.getSize(),photos.length);

        if(!headerImg.isEmpty()) {
            // 获取原始的文件名作为存储后的文件名
            String originalFilename = headerImg.getOriginalFilename();
            // 保存图片到服务器，OSS服务器
            headerImg.transferTo(new File("D:\\Java文件上传\\"+originalFilename));
        }

        if(photos.length > 0) {
            for (MultipartFile photo : photos) {
                if (!photo.isEmpty()) {
                    String originalFilename = photo.getOriginalFilename();
                    photo.transferTo(new File("D:\\Java文件上传\\"+originalFilename));
                }
            }
        }


        return "main";
    }
}
